package com.link2room.aeriabots.facade.impl;

import com.link2room.aeriabots.dto.result.base.WxMemberInfoResDto;
import com.link2room.aeriabots.entity.WxCertificate;
import com.link2room.aeriabots.entity.WxMemberInfo;
import com.link2room.aeriabots.facade.IWXMemberInfoFacadeService;
import com.link2room.aeriabots.thread.task.SaveWxMemberInfoTask;
import com.link2room.aeriabots.thread.task.WxUserInfoSaveTask;
import com.link2room.aeriabots.thread.util.ThreadUtil;
import com.link2room.common.dto.param.base.BaseL2rParamDto;
import com.link2room.common.dto.result.base.MemberSessionDto;
import com.link2room.common.dto.threadlocal.ApiThreadLocal;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.jpa.result.QueryResult;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.ClassConverUtil;
import com.link2room.common.util.JacksonUtil;
import com.link2room.common.util.StringUtil;
import com.link2room.enums.exception.AeriabotsSysExceptionEnum;
import com.tencent.client.OfficialAccountClient;
import com.tencent.protocol.component.user_info_protocol.UserInfoResData;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LN on 2016/11/15.
 */
@Component("wxMemberInfoFacadeService")
public class WXMemberInfoFacadeServiceImpl extends BaseFacade implements IWXMemberInfoFacadeService {
    @Resource
    private ICommonService commonService;

    @Override
    public List<WxMemberInfoResDto> getMemberInfos(BaseL2rParamDto paramDto) throws Exception {
        String hotelGroupCode = paramDto.getLhotelGroupCode();
        String openid = paramDto.getOpenid();
        if(StringUtil.isBlank(hotelGroupCode)||StringUtil.isBlank(openid)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(), BaseSysExceptionEnum.INVALID_PARA.getMsg()+"hotelGroupCode和openid都不能为空", BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }

        WxMemberInfo find = new WxMemberInfo();
        find.setLhotelGroupCode(hotelGroupCode);
        find.setOpenid(openid);
        QueryResult<WxMemberInfo> res = commonService.findAllEQ(WxMemberInfo.class, find);
        if(res.getResultlist()!=null&&res.getResultlist().size()>0){
            List<WxMemberInfoResDto> resDtoList = new ArrayList<>();
            for(int i = 0;i<res.getResultlist().size();i++){
                WxMemberInfoResDto resDto = new WxMemberInfoResDto();

                ClassConverUtil.copyProperties(res.getResultlist().get(i),resDto);
                resDtoList.add(resDto);
            }
            return resDtoList;
        }else if(StringUtil.isNotBlank(openid)){
            List<WxMemberInfoResDto> resDtoList = new ArrayList<>();
            WxMemberInfoResDto resDto = new WxMemberInfoResDto();
            WxMemberInfo info = requestMemberInfo(hotelGroupCode,openid);
            ClassConverUtil.copyProperties(info,resDto);
            resDtoList.add(resDto);
            return resDtoList;
        }
        return null;
    }

    @Override
    public WxMemberInfoResDto getCurrentMemberInfo() throws Exception {
        MemberSessionDto memberSessionDto = ApiThreadLocal.getMemberSessionThreadLocal();
        String openid = memberSessionDto.getOpenid();
        String lhotelGroupCode = memberSessionDto.getLhotelGroupCode();
        WxMemberInfo find = new WxMemberInfo();
        find.setLhotelGroupCode(lhotelGroupCode);
        find.setOpenid(openid);
        WxMemberInfo qres = commonService.findOneEQ(WxMemberInfo.class, find);
        if(qres != null){
            return ClassConverUtil.copyProperties(qres,WxMemberInfoResDto.class);
        }else {
            WxMemberInfo info = requestMemberInfo(lhotelGroupCode,openid);
            return ClassConverUtil.copyProperties(info,WxMemberInfoResDto.class);
        }
    }

    private WxMemberInfo requestMemberInfo(String hotelGroupCode ,String openid ) throws Exception {
        WxCertificate wc = getWxCertificate(hotelGroupCode, null);
        String accessToken  = wc.getAccessToken();
        if(StringUtil.isBlank(accessToken) || StringUtil.isBlank(openid)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA);
        }
        String result = OfficialAccountClient.requestUserInfo(accessToken, openid,null);
        if(StringUtil.isBlank(result)){
            throw new SysException(AeriabotsSysExceptionEnum.WX_SDK_ERROR.getCode(),
                    AeriabotsSysExceptionEnum.WX_SDK_ERROR.getMsg()+"requestUserInfo:accessToken"+accessToken+" openid:"+openid,
                    AeriabotsSysExceptionEnum.WX_SDK_ERROR.getBizType());
        }
        WxMemberInfo wxMemberInfo = new WxMemberInfo();
        UserInfoResData res = JacksonUtil.jsonToBean(result, UserInfoResData.class);
        if(StringUtil.isNotBlank(res.getOpenid())){
            wxMemberInfo.setLhotelGroupCode(hotelGroupCode);
            wxMemberInfo.setUnionid(res.getUnionid());
            wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
            wxMemberInfo.setCity(res.getCity());
            wxMemberInfo.setCountry(res.getCountry());
            wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
            wxMemberInfo.setProvince(res.getProvince());
            wxMemberInfo.setSex(res.getSex().toString());
            wxMemberInfo.setNickname(WxUserInfoSaveTask.EmojiFilter.filterEmoji(res.getNickname()));
            wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
            wxMemberInfo.setCity(res.getCity());
            wxMemberInfo.setOpenid(openid);
            wxMemberInfo.setCountry(res.getCountry());
            wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
            wxMemberInfo.setProvince(res.getProvince());
            wxMemberInfo.setSex(res.getSex().toString());
            wxMemberInfo.setNickname(res.getNickname());
        }else{
            throw new SysException(AeriabotsSysExceptionEnum.WX_SDK_ERROR.getCode(),
                    AeriabotsSysExceptionEnum.WX_SDK_ERROR.getMsg()+"requestUserInfo:[errorCode]"+res.getErrcode()+" [errorMsg]:"+res.getErrmsg(),
                    AeriabotsSysExceptionEnum.WX_SDK_ERROR.getBizType());
        }
        //异步保存memberInfo
        ThreadUtil.getExecutor().submit(new SaveWxMemberInfoTask(wxMemberInfo));
        return wxMemberInfo;
    }
}
